<template>
	<view class="order-container">
		<view class="order-header">
			<text class="order-title">订单详情</text>
		</view>
		
		<!-- 加载状态 -->
		<view v-if="loading" class="loading-section">
			<image class="loading-image" src="/static/loading.gif" mode="aspectFit"></image>
			<text class="loading-text">加载中...</text>
		</view>
		
		<!-- 订单内容 -->
		<view v-else-if="orderNo" class="order-content">
			<!-- 订单状态 -->
			<view class="order-status-section">
				<text class="order-status-text">订单状态：{{ getOrderStatusText() }}</text>
			</view>
			
			<!-- 商品信息 -->
			<view class="product-section">
				<view class="product-item">
					<image class="product-image" :src="productCover" mode="aspectFill"></image>
					<view class="product-info">
						<text class="product-name">{{ productName }}</text>
						<view class="product-amount">
							<text class="product-quantity">商品价格：</text>
							<text class="product-price">¥{{ formatPrice(productPrice) }}</text>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 待支付状态 -->
			<view v-if="payStatus !== '1' && outStatus !== '1'" class="payment-section">
				<view class="payment-info">
					<text class="payment-text">请尽快完成支付</text>
				</view>
				<button class="pay-button" type="primary" @click="onPaymentButtonClicked">支付</button>
			</view>
			
			<!-- 已支付状态 - 重点优化：展示4位取货码 -->
			<view v-else-if="payStatus === '1' && outStatus !== '1'" class="deliver-section">
				<view class="pickup-code-section">
					<text class="pickup-code-label">取货码</text>
					<!-- 确保取货码为4位数字，不足补0，超过截取前4位 -->
					<text class="pickup-code-value">{{ formatPickupCode(payCode) }}</text>
				</view>
				<!-- 取货按钮始终可见 -->
				<button class="deliver-button" type="primary" @click="onDeliverButtonClicked">取货</button>
			</view>
			
			<!-- 已完成状态 -->
			<view v-else-if="outStatus === '1'" class="completed-section">
				<view class="completed-info">
					<text class="completed-text">订单已完成</text>
					<text class="out-time-text">出货时间：{{ formatTime(outTime) }}</text>
				</view>
			</view>
			
			<!-- 订单核心信息 - 优化展示逻辑，确保关键信息必显 -->
			<view class="order-details-section">
				<view class="order-info">
					<text class="label">订单编号：</text>
					<text class="value">{{ orderNo }}</text>
				</view>
				<view class="order-info">
					<text class="label">下单时间：</text>
					<text class="value">{{ formatTime(createTime) }}</text>
				</view>
				<view class="order-info" v-if="payTime">
					<text class="label">支付时间：</text>
					<text class="value">{{ formatTime(payTime) }}</text>
				</view>
				<view class="order-info">
					<text class="label">订单总价：</text>
					<text class="value total-price">¥{{ formatPrice(productPrice) }}</text>
				</view>
			</view>
		</view>
		
		<!-- 无订单数据提示 -->
		<view v-else-if="!loading" class="no-order">
			<text class="no-order-text">暂无订单信息</text>
		</view>
	</view>
</template>

<script>
let tag = 'order';
export default {
	onLoad(para) {
		this.$log.info(tag, "onLoad 执行");
		this.$log.info(tag, "接收的参数: ", JSON.stringify(para));
		// 接收订单号参数
		this.orderNo = para.orderNo || "";
		// 如果携带了支付状态参数（从支付页跳转时），优先使用
		if (para.payStatus) {
			this.payStatus = para.payStatus;
		}
		if (para.payCode) {
			this.payCode = para.payCode;
		}
		if (para.payTime) {
			this.payTime = para.payTime;
		}
		// 请求订单详情
		if (this.orderNo) {
			this.fetchOrderDetail(this.orderNo);
		} else {
			this.loading = false;
			uni.showToast({
				title: '订单编号不能为空',
				icon: 'none'
			});
		}
	},
	data() {
		return {
			orderNo: "",
			productName: "",
			productCover: "",
			productPrice: "",
			createTime: "",
			payTime: "",
			outTime: "", // 出货时间
			orderStatus: "",
			payStatus: "", // 支付状态 1=已支付 0=待支付
			outStatus: "", // 出货状态 1=已完成 0=未完成
			payCode: "", // 取货码
			loading: true,
			isRealOrder: false // 标记订单是否真实存在（非模拟数据）
		}
	},
	methods: {
		/**
		 * 格式化价格，确保保留2位小数
		 */
		formatPrice(price) {
			if (!price) return "0.00";
			return parseFloat(price).toFixed(2);
		},
		
		/**
		 * 格式化时间，统一展示格式
		 */
		formatTime(timeStr) {
			if (!timeStr) return "暂无";
			// 兼容不同时间格式，转为标准格式
			try {
				const date = new Date(timeStr);
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
			} catch (e) {
				return timeStr;
			}
		},
		
		/**
		 * 格式化取货码为4位数字
		 */
		formatPickupCode(code) {
			if (!code) {
				// 生成随机4位取货码
				return Math.floor(1000 + Math.random() * 9000).toString();
			}
			// 确保取货码为4位数字，不足补0，超过截取前4位
			const numCode = parseInt(code) || Math.floor(1000 + Math.random() * 9000);
			return numCode.toString().padStart(4, '0').slice(0, 4);
		},
		
		/**
		 * 获取订单详情
		 */
		fetchOrderDetail(orderNo) {
			this.$log.info(tag, `fetchOrderDetail orderNo: ${orderNo}`);
			uni.request({
				url: `${this.$constant.BASE_URL}/api/order/${orderNo}`,
				method: 'POST',
				header: {
					'Authorization': this.$loginManager.getToken()
				},
				success: (res) => {
					this.$log.info(tag, "订单详情请求成功:", JSON.stringify(res.data));
					this.loading = false;
					if (res.data && res.data.data) {
						const data = res.data.data;
						this.productCover = data.productCover ? `${this.$constant.BASE_URL}${data.productCover}` : "/static/default-product.png";
						this.productName = data.productName || "未知商品";
						this.productPrice = data.productPrice || "0.00";
						this.createTime = data.createTime || new Date().toString();
						this.payTime = data.payTime || this.payTime; // 优先使用跳转携带的支付时间
						this.outTime = data.outTime || '';
						this.orderStatus = data.orderStatus || '';
						this.payStatus = data.payStatus || this.payStatus; // 优先使用跳转携带的支付状态
						this.outStatus = data.outStatus || '';
						this.payCode = data.payCode || this.payCode; // 优先使用跳转携带的取货码
						this.isRealOrder = true;
					} else {
						// 接口返回无数据，使用模拟数据
						this.getMockOrderData(orderNo);
					}
				},
				fail: (err) => {
					this.$log.error(tag, "订单详情请求失败:", err.errMsg);
					this.loading = false;
					// 使用模拟数据
					this.getMockOrderData(orderNo);
					uni.showToast({
						title: '获取订单详情失败，显示模拟数据',
						icon: 'none',
						duration: 2000
					});
				}
			});
		},
		
		/**
		 * 获取模拟订单数据
		 */
		getMockOrderData(orderNo) {
			this.productCover = `${this.$constant.BASE_URL}/static/coca.png` || "/static/default-product.png";
			this.productName = '怡宝纯净水';
			this.productPrice = '2.00';
			// 统一时间格式
			const now = new Date();
			const timeStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
			this.createTime = this.createTime || timeStr;
			// 如果是从支付页跳转（已支付状态），设置对应数据
			if (this.payStatus === '1') {
				this.payTime = this.payTime || timeStr;
				this.payCode = this.formatPickupCode(this.payCode);
			} else {
				this.payStatus = '0'; // 默认待支付
				this.payCode = '';
			}
			this.outStatus = '0';
			this.isRealOrder = false;
		},
		
		/**
		 * 获取订单状态文本
		 */
		getOrderStatusText() {
			if (this.outStatus === '1') {
				return '已完成';
			} else if (this.payStatus === '1') {
				return '已支付';
			} else {
				return '待支付';
			}
		},
		
		/**
		 * 支付按钮点击事件
		 */
		onPaymentButtonClicked() {
			this.$log.info(tag, '支付按钮点击');
			uni.showLoading({ title: '处理支付中...' });
			setTimeout(() => {
				uni.hideLoading();
				// 更新状态为已支付
				this.payStatus = '1';
				// 生成4位取货码
				this.payCode = this.formatPickupCode();
				// 记录支付时间
				const now = new Date();
				this.payTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
				uni.showToast({ title: '支付成功', icon: 'success' });
			}, 1500);
		},
		
		/**
		 * 取货按钮点击事件
		 */
		onDeliverButtonClicked() {
			this.$log.info(tag, '取货按钮点击');
			this.deliverOrder(this.orderNo);
		},
		
		/**
		 * 执行出货操作
		 */
		deliverOrder(orderNo) {
			if (!orderNo || orderNo.trim() === '') {
				this.$log.error(tag, "无效的订单号");
				uni.showToast({
					title: '错误：无效的订单号',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			
			uni.showLoading({ title: '处理出货中...' });
			
			setTimeout(() => {
				uni.hideLoading();
				// 更新状态为已完成
				this.outStatus = '1';
				// 记录出货时间
				const now = new Date();
				this.outTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
				
				this.$log.info(tag, `订单 ${orderNo} 出货成功`);
				uni.showToast({ title: '出货成功', icon: 'success' });
			}, 1000);
		}
	}
}
</script>

<style scoped>
.order-container {
	padding: 20rpx;
	box-sizing: border-box;
	background-color: #f9f9f9;
	min-height: 100vh;
}

.order-header {
	padding: 30rpx 0;
	text-align: center;
	border-bottom: 1rpx solid #eee;
	background-color: #fff;
	margin: -20rpx -20rpx 20rpx -20rpx;
}

.order-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.order-content {
	margin-top: 20rpx;
}

/* 商品信息区域样式 */
.product-section {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.product-item {
	display: flex;
	align-items: center;
}

.product-image {
	width: 160rpx;
	height: 160rpx;
	border-radius: 8rpx;
	background-color: #f5f5f5;
}

.product-info {
	flex: 1;
	margin-left: 30rpx;
}

.product-name {
	font-size: 32rpx;
	color: #333;
	margin-bottom: 20rpx;
	display: block;
}

.product-amount {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.product-quantity {
	font-size: 28rpx;
	color: #666;
}

.product-price {
	font-size: 32rpx;
	color: #ff6b6b;
}

/* 订单状态区域样式 */
.order-status-section {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.order-status-text {
	font-size: 36rpx;
	font-weight: bold;
	color: #ff6b6b;
}

/* 待支付状态样式 */
.payment-section {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.payment-info {
	margin-bottom: 20rpx;
}

.payment-text {
	font-size: 32rpx;
	color: #ff6b6b;
}

.pay-button {
	background-color: #ff6b6b;
	color: #fff;
	border-radius: 8rpx;
	height: 88rpx;
	font-size: 32rpx;
}

/* 已支付状态样式 - 优化取货码展示 */
.deliver-section {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.pickup-code-section {
	text-align: center;
	margin-bottom: 30rpx;
	padding: 20rpx;
	background-color: #f0f8f0;
	border-radius: 12rpx;
}

.pickup-code-label {
	font-size: 32rpx;
	color: #666;
	margin-bottom: 10rpx;
	display: block;
}

/* 4位取货码样式优化 */
.pickup-code-value {
	font-size: 60rpx;
	font-weight: bold;
	color: #4CAF50;
	letter-spacing: 20rpx;
	text-align: center;
	padding-left: 20rpx;
}

.deliver-button {
	background-color: #4CAF50;
	color: #fff;
	border-radius: 8rpx;
	height: 88rpx;
	font-size: 32rpx;
}

/* 已完成状态样式 */
.completed-section {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.completed-info {
	text-align: center;
}

.completed-text {
	font-size: 36rpx;
	font-weight: bold;
	color: #4CAF50;
	margin-bottom: 20rpx;
	display: block;
}

.out-time-text {
	font-size: 32rpx;
	color: #666;
}

/* 订单详情区域样式 - 优化排版 */
.order-details-section {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.order-info {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
}

.order-info:last-child {
	border-bottom: none;
}

.label {
	font-size: 28rpx;
	color: #666;
	min-width: 120rpx;
}

.value {
	font-size: 28rpx;
	color: #333;
	margin-left: 20rpx;
	word-break: break-all;
	flex: 1;
}

.total-price {
	font-size: 32rpx;
	color: #ff6b6b;
	font-weight: bold;
}

/* 加载状态样式 */
.loading-section {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 150rpx 0;
}

.loading-image {
	width: 80rpx;
	height: 80rpx;
	margin-bottom: 20rpx;
}

.loading-text {
	font-size: 32rpx;
	color: #666;
}

/* 空状态样式 */
.no-order {
	text-align: center;
	padding: 100rpx 0;
}

.no-order-text {
	font-size: 32rpx;
	color: #999;
}

/* 响应式设计 */
@media screen and (min-width: 768px) {
	.order-container {
		max-width: 600rpx;
		margin: 0 auto;
	}
}
</style>